from django.shortcuts import render,get_object_or_404
from django.http import HttpResponse,HttpResponseRedirect
from .models import Choice, Question, Book, NewsUser
from django.db.models import F
from django.urls import reverse
from rest_framework.views import APIView
from rest_framework import serializers
from rest_framework.response import Response



# 视图层

def index(request):
    latest_question_list = Question.objects.order_by("-pub_date")[:5]   # 按发布日期倒序查询到问题列表
    context = {"latest_question_list": latest_question_list}            # 将查询结果复制给变量
    # template = loader.get_template("polls/index.html")                # 加载polls下的模板文件
    # return HttpResponse(template.render(context, request))            # 将模板和变量渲染后返回
    return render(request, "polls/index.html", context)    # 使用render函数将模板和变量渲染后返回

def detail(request, question_id):
    # try:
    #     question = Question.objects.get(pk=question_id)
    # except:
    #     raise  Http404("这个问题不存在")                                    # 抛出异常
    # else:
    #     return render(request, "polls/index.html",  {"question": question})
    # 优化后
    question = get_object_or_404(Question, pk=question_id)
    return render(request, "polls/detail.html", {"question": question})

def results(request, question_id):
    question = get_object_or_404(Question, pk=question_id)
    response = "你正在看的结果属于问题： %s."
    return render(request, "polls/results.html", {"question": question})

def vote(request, question_id):
    question = get_object_or_404(Question, pk=question_id)
    try:
        selected_choice = question.choice_set.get(pk=request.POST["choice"])
    except(KeyError, Choice.DoesNotExist):
        context = {
            "question": question,
            "error_message": "You didn't select a choice."
        }
        return render(request, "polls/detail", context)
    else:
        selected_choice.votes = F("votes") + 1
        selected_choice.save()
        return HttpResponseRedirect(reverse("polls:results", args=(question.id,)))



class BookSerializer(serializers.Serializer):
    id = serializers.IntegerField(read_only=True)
    name = serializers.CharField()
    cbans = serializers.CharField()

    def create(self, validated_data):
        instance = Book.objects.create(**validated_data)
        return instance

    def update(self, instance, validated_data):
        instance.name = validated_data.get("name")
        instance.cbans = validated_data.get("cbans")
        instance.save()
        return instance


class Booksview(APIView):

    def get(self, request):
        book_ob = Book.objects.all()
        serializer = BookSerializer(instance=book_ob, many=True)
        # 返回序列化后的数据
        return Response({
            "code": "200",
            "data": serializer.data
        })

    def post(self, request):
        ser = BookSerializer(data=request.data)
        if ser.is_valid():
            ser.save()
            return Response({
                "code": "200",
                "data":ser.validated_data
            })
        else:
            print(ser.errors)
            return Response({
                "code": "500",
                "data":ser.errors
            })





class Booksdetailview(APIView):

    def get(self, request, pk):
        book_ob = Book.objects.get(pk=pk)
        serializer = BookSerializer(instance=book_ob, many=False)   # 不需要多条数据
        return Response({
            "code": "200",
            "data": serializer.data
        })

    def put(self, request, pk):
        book_ob = Book.objects.filter(pk=pk)
        ser = BookSerializer(instance=book_ob, data=request.data)
        if ser.is_valid():
            return Response({
                "code": "200",
                "data": ser.validated_data
            })
        else:
            print(ser.errors)
            return Response({
                "code": "500",
                "data": ser.errors
            })


    def delete(self, request, pk):
        Book.objects.get(pk=pk).delete()
        return Response({
                "code": "200",
                "data": "删除成功"
            })

class RegisterSerializer(serializers.Serializer):
    id = serializers.IntegerField(read_only=True)
    username = serializers.CharField()
    password = serializers.CharField()
    email = serializers.CharField()
    gender = serializers.IntegerField()

    def create(self, validated_data):
        instance = NewsUser.objects.create(**validated_data)
        return instance

    # def update(self, instance, validated_data):
    #     instance.name = validated_data.get("name")
    #     instance.cbans = validated_data.get("cbans")
    #     instance.save()
    #     return instance



# 新闻网站注册页面
class Register(APIView):
    def post(self, request):
        ser = RegisterSerializer(data=request.data)
        if ser.is_valid():
            ser.save()
            return Response({
                "code": "200",
                "message":"注册成功",
                "data": ser.validated_data
            })
        else:
            print(ser.errors)
            return Response({
                "code": "500",
                "message": "注册失败",
                "data": ser.errors
            })



class AuthSerializer(serializers.Serializer):
    username = serializers.CharField()
    password = serializers.CharField()




# 新闻网站用户登录信息获取页面
class Auth(APIView):

    def post(self, request):
        ser = AuthSerializer(data=request.data)
        if ser.is_valid():
            try:
                user = NewsUser.objects.get(username=ser.validated_data["username"])
                if ser.validated_data["password"] == user.password:  # 检查密码是否正确
                    return Response({
                        "code": "200",
                        "message": "登录成功",
                    })
                else:
                    return Response({
                        "code": "501",
                        "message": "密码错误",
                    })
            except:
                return Response({
                    "code": "502",
                    "message": "用户不存在",
                })